package com.koron.css2.serviceManage.impl;

import com.koron.css2.ServerInterface;
import com.koron.css2.serviceManage.bean.RequestBean;
import com.koron.css2.serviceManage.bean.ServiceUserBean;
import com.koron.css2.serviceManage.bean.UserInfoBean;
import com.koron.css2.serviceManage.mapper.ServiceUserMapper;
import com.koron.css2.serviceManage.utils.JsonUtils;
import com.koron.util.Constant;
import com.koron.util.Tools;
import com.mysql.cj.util.StringUtils;
import org.bson.types.ObjectId;
import org.koron.ebs.mybatis.SessionFactory;
import org.swan.bean.MessageBean;

import java.util.List;

public class SysUserAdd implements ServerInterface {

	@Override
	public MessageBean<?> exec(SessionFactory factory, UserInfoBean userInfo, RequestBean req) {

		@SuppressWarnings("rawtypes")
		MessageBean<List> info = MessageBean.create(Constant.MESSAGE_INT_SUCCESS, "success", List.class);

		try {
			ServiceUserBean bean = JsonUtils.objectToPojo(req.getData(), ServiceUserBean.class);
			ServiceUserMapper mapper = factory.getMapper(ServiceUserMapper.class);
			if (StringUtils.isNullOrEmpty(bean.getLoginName())) {
				info.setCode(Constant.MESSAGE_INT_FAIL);
				info.setDescription("登录名不能为空");
				return info;
			}
			if (StringUtils.isNullOrEmpty(bean.getPassword())) {
				return MessageBean.create(Constant.MESSAGE_INT_FAIL, "密码不能为空", void.class);
			}
			if (!bean.getPassword().equals(bean.getCheckPass())) {
				return MessageBean.create(Constant.MESSAGE_INT_FAIL, "两次密码不一致", void.class);
			}
			ServiceUserBean serviceUserBean = mapper.selectByLoginName(bean);
			if (serviceUserBean != null) {
				return MessageBean.create(Constant.MESSAGE_INT_FAIL, "已存在该账号信息", Void.class);
			} else {
				bean.setId(new ObjectId().toHexString());
				bean.setPassword(Tools.MD5(bean.getPassword()));
				mapper.insert(bean);
			}
		} catch (Exception e) {
			info.setCode(Constant.MESSAGE_INT_FAIL);
			info.setDescription(e.getMessage());
			logger.error(e.getMessage(), e);
		}
		return info;
	}

}
